//
//  SYS_MessageMemberDetailVC.m
//  System_App
//
//  Created by 魏配军 on 2017/12/5.
//  Copyright © 2017年 czy001. All rights reserved.
//

#import "SYS_MessageMemberDetailVC.h"
#import "SYS_MemberDetailCell.h"
#import "SYS_MemberDetailModel.h"
#import "SYS_SuitTextAndIconView.h"
#import "SYS_SuitIconAndTextView.h"
#import "SYS_MemberDetail1Cell.h"

@interface SYS_MessageMemberDetailVC ()<UITableViewDelegate,UITableViewDataSource>
{
    UIImageView *navBarHairlineImageView;
    UIImageView *bgImageView;
}
@property (nonatomic, strong) DSNewTableView *mainTableView;
/***************员工详细资料*****************/
@property (nonatomic,strong) SYS_MemberDetailModel *detailModel;
@property (nonatomic,strong) UIImageView *iconImageView;
@property (nonatomic,strong) SYS_SuitTextAndIconView *nameView;
@property (nonatomic,strong) UILabel *phoneLabel;
@end

@implementation UIImage (ColorImage)
+ (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
@end

@implementation SYS_MessageMemberDetailVC

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    navBarHairlineImageView.hidden = YES;
}

//在页面消失的时候就让出现
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
    navBarHairlineImageView.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self setNavigationBar];
    [self initWithUI];
    
}

#pragma mark -- setter and getter
- (void)setNavigationBar{
    self.title = @"详细资料";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"SYS_Public_back" highImage:nil title:nil target:self action:@selector(backToPrevious)];
    self.view.backgroundColor = DGHColor(242, 242, 242);
    
    //再定义一个imageview来等同于导航条底部的黑线
    navBarHairlineImageView=[UIImageView new];
    navBarHairlineImageView = [DSUtility findHairlineImageViewUnder:self.navigationController.navigationBar];
    navBarHairlineImageView.image = [UIImage imageWithColor:MainColor];
}

#pragma mark   -------  UI  ---------
-(void) initWithUI
{
    UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0, -StatusBarHeight, SCREENWIDTH, 250)];
    headView.backgroundColor=DGHColor(242, 242, 242);
    [self.view addSubview:headView];
    
    bgImageView=[UIImageView new];
    bgImageView.image=[UIImage imageNamed:@"message_memberBigBg"];
    bgImageView.userInteractionEnabled=YES;
    [headView sd_addSubviews:@[bgImageView]];
    
    bgImageView.sd_layout
    .leftSpaceToView(headView, 0)
    .topSpaceToView(headView, 0)
    .widthIs(SCREENWIDTH)
    .heightIs(220);
    
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    leftBtn.frame=CGRectMake(15, 10+StatusBarHeight, 11, 22);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"SYS_Public_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backToPrevious) forControlEvents:UIControlEventTouchUpInside];
    [bgImageView addSubview:leftBtn];
    
    UILabel *titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(30, 12+StatusBarHeight, SCREENWIDTH-60, 20)];
    titleLabel.textColor=DSCOLOR_WHITE;
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.font=[UIFont fontWithName:@"PingFangSC-Medium" size:18];
    titleLabel.text=@"详细资料";
    [bgImageView addSubview:titleLabel];
    
    _iconImageView=[UIImageView new];
    _iconImageView.layer.masksToBounds=YES;
    _iconImageView.layer.cornerRadius=30;
    _iconImageView.layer.borderWidth=4;
    _iconImageView.layer.borderColor=MainColor.CGColor;
    
    [bgImageView sd_addSubviews:@[_iconImageView]];
    
    _iconImageView.sd_layout
    .leftSpaceToView(bgImageView, (SCREENWIDTH-60)/2)
    .topSpaceToView(titleLabel, 20)
    .widthIs(60)
    .heightIs(60);
    
    _nameView=[[SYS_SuitTextAndIconView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(titleLabel.frame)+85, SCREENWIDTH-120, 20)];
    [bgImageView addSubview:_nameView];
    
    _phoneLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(_nameView.frame)+10, SCREENWIDTH-20, 20)];
    _phoneLabel.textColor=DSCOLOR_WHITE;
    _phoneLabel.textAlignment=NSTextAlignmentCenter;
    _phoneLabel.font=[UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [bgImageView addSubview:_phoneLabel];
    
    UIView *bottomBgView=[[UIView alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(_phoneLabel.frame)+10, SCREENWIDTH-40, 40)];
    bottomBgView.backgroundColor=DSCOLOR_WHITE;
    bottomBgView.layer.masksToBounds=YES;
    bottomBgView.layer.cornerRadius=20;
    [bgImageView addSubview:bottomBgView];
    
    SYS_SuitIconAndTextView *phoneView=[[SYS_SuitIconAndTextView alloc]initWithFrame:CGRectMake(0, 0,(SCREENWIDTH-40)/2 , 40)];
    phoneView.iconImageView.image=[UIImage imageNamed:@"message_bodadh"];
    phoneView.nameLabel.text=@"拨打电话";
    phoneView.userInteractionEnabled=YES;
    UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(phoneViewToPhone)];
    [phoneView addGestureRecognizer:ges];
    [bottomBgView addSubview:phoneView];
    
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake((SCREENWIDTH-40)/2, 5, 0.5, 30)];
    lineView.backgroundColor=DGHColor(221, 221, 221);
    [bottomBgView addSubview:lineView];
    
    SYS_SuitIconAndTextView *sendMessageView=[[SYS_SuitIconAndTextView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(lineView.frame)+1, 0,(SCREENWIDTH-40)/2 , 40)];
    sendMessageView.isSetFrame=YES;
    sendMessageView.iconImageView.image=[UIImage imageNamed:@"message_fasongxx"];
    sendMessageView.nameLabel.text=@"发送信息";
    sendMessageView.userInteractionEnabled=YES;
    UITapGestureRecognizer *ges1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sendMessageToSend)];
    [sendMessageView addGestureRecognizer:ges1];
    [bottomBgView addSubview:sendMessageView];
    
    _mainTableView=[[DSNewTableView alloc] initWithFrame:CGRectMake(0, -StatusBarHeight, SCREENWIDTH, SCREENHEIGHT+StatusBarHeight) style:UITableViewStylePlain];
    _mainTableView.delegate=self;
    _mainTableView.dataSource=self;
    _mainTableView.backgroundColor=DGHColor(242, 242, 242);
    _mainTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _mainTableView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:_mainTableView];
    
    _mainTableView.tableHeaderView=headView;
    //加载详细资料
    _detailModel=[SYS_MemberDetailModel new];
    [self requestDetailData];
}

#pragma mark   ----------拨打电话 和 发送信息-------------
-(void) phoneViewToPhone
{
    NSLog(@"拨打电话");
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",_detailModel.phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

}

-(void) sendMessageToSend
{
    NSLog(@"发送信息");
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:_detailModel.imKey conversationType:EMConversationTypeChat];
    chatController.title=_detailModel.employeesName;
    
    DSDataBaseOperation *_operation=[[DSDataBaseOperation alloc]init];
    DGHUserInfo *info=[_operation searchUserInfoWithHXName:_detailModel.imKey];
    if (!(info.headpic || info.username)) {
        EMMessage *mes=[[EMMessage alloc] initWithConversationID:nil from:_detailModel.imKey to:_detailModel.imKey body:nil ext:@{@"name":_detailModel.employeesName,@"image":_detailModel.userLogo}];
        [_operation insertUserInfo:mes];
    }
 
    [self.navigationController pushViewController:chatController animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}

#pragma mark   ----------请求详细资料-------------
-(void) requestDetailData
{
    NSString *session=[SYS_LoginModel instance].sessionInfo.session;
    UICKeyChainStore *keychainStore = [UICKeyChainStore keyChainStore];
    NSString *pid = [keychainStore stringForKey:@"pid"];
    NSDictionary *parma=@{@"session":session,@"storeEmployeesId":_storeEmployeesId,@"pid":pid};
    [self showHudInView:self.view hint:@"正在加载..."];
    [SYS_HttpUtility getSingleEmployeInfoRequest:parma success:^(id returnValue) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([returnValue[@"flag"] isEqualToString:@"true"]) {
            NSDictionary *dic=returnValue[@"data"];
            _detailModel=[SYS_MemberDetailModel mj_objectWithKeyValues:dic];
            
            [_iconImageView sd_setImageWithURL:[NSURL URLWithString:_detailModel.userLogo] placeholderImage:[UIImage imageNamed:@"public_people"]];
            [self getStoreAdderssWidthByStoreName:_detailModel.employeesName andSex:_detailModel.sex];
            _phoneLabel.text=FORMAT(@"昵称：%@  %@",_detailModel.nickName,_detailModel.positionName);
            [_mainTableView reloadData];
        }else{
            [MBProgressHUD showSuccess:returnValue[@"exp"] toView:self.view];
        }
    } failure:^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        RequestFailure;
    }];
    
}

#pragma mark   ----------UITableViewDelegate,UITableViewDataSource-------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 2;
            break;
        case 1:
            return 3;
            break;
        default:
            break;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SYS_MemberDetailCell *cell = [[SYS_MemberDetailCell alloc]initWithTableView:tableView reuseId:@"SYS_MemberDetailCell"];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            cell.iconImageView.image=[UIImage imageNamed:@"message_huiyuanshu"];
            cell.nameLabel.text=@"会员数";
            cell.explainLabel.text=_detailModel.storeEmployeesMembersCount;
        }else if (indexPath.row==1){
            cell.iconImageView.image=[UIImage imageNamed:@"message_fuwudan"];
            cell.nameLabel.text=@"服务单";
            cell.explainLabel.text=_detailModel.serviceOrderCount;
        }
    }else if (indexPath.section==1){
        if (indexPath.row==0) {
            cell.iconImageView.image=[UIImage imageNamed:@"message_sjhm"];
            cell.nameLabel.text=@"手机号码";
            cell.explainLabel.text=_detailModel.contact;
        }else if (indexPath.row==1){
            cell.iconImageView.image=[UIImage imageNamed:@"message_gznx"];
            cell.nameLabel.text=@"工作年限";
            cell.explainLabel.text=FORMAT(@"%@年",_detailModel.jobYear);
        }else if (indexPath.row==2){
            SYS_MemberDetail1Cell *cell = [[SYS_MemberDetail1Cell alloc]initWithTableView:tableView reuseId:@"SYS_MemberDetail1Cell"];
            cell.iconImageView.image=[UIImage imageNamed:@"message_scly"];
            cell.nameLabel.text=@"擅长领域";
            if (_detailModel.labels.length>0) {
                NSArray *array = [_detailModel.labels componentsSeparatedByString:@","];
                cell.labelArray=array;
            }
            return cell;
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        if (indexPath.row==2) {
            if (_detailModel.labels.length>0) {
                NSArray *array = [_detailModel.labels componentsSeparatedByString:@","];
                if (array.count%3==0) {
                    return 100+50*(array.count/3-1);

                }else{
                    return 100+50*(array.count/3);
                }
            }
            return 50;
        }
    }
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==0) {
        return 5;
    }
    return 0.01;
}

- (void)getStoreAdderssWidthByStoreName:(NSString *)storeName  andSex:(NSString *)sex{

    if ([sex isEqualToString:@"1"]) {
        _nameView.iconImageView.image=[UIImage imageNamed:@"message_nan"];
    }else{
        _nameView.iconImageView.image=[UIImage imageNamed:@"message_nv"];

    }
    _nameView.nameLabel.text =storeName;
    _nameView.nameLabel.textColor=[UIColor whiteColor];
    float nameWidth = [DSUtility getStringWidth:_nameView.nameLabel.text front:DSFONT];
    _nameView.frame=CGRectMake(60, StatusBarHeight + 117, SCREENWIDTH-120, 30);
    nameWidth = MIN(DSDeviceSize.width - 60, nameWidth);
    _nameView.nameLabel.width = MIN(nameWidth, DSDeviceSize.width - 150);
    _nameView.nameLabel.x =(SCREENWIDTH-120-_nameView.nameLabel.width-15)/2;
    _nameView.iconImageView.x = CGRectGetMaxX(_nameView.nameLabel.frame)+5;
    
}


- (void)backToPrevious
{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
